using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Command.Host.Infrastructure
{
    public class JasonServiceHost : ServiceHost
    {
        private readonly IServiceProvider _serviceProvider;

        public JasonServiceHost(IServiceProvider serviceProvider, Type serviceType, params Uri[] baseAddresses) 
            : base(serviceType, baseAddresses)
        {
            _serviceProvider = serviceProvider;

            Description.Behaviors.Add
                    (
                        new ServiceMetadataBehavior
                        {
                            HttpGetEnabled = true,
                            MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
                        }
                    );
        }

        protected override void OnOpening()
        {
            Description.Behaviors.Add(new DependencyInjectionServiceBehavior(_serviceProvider));

            var behavior = Description.Behaviors.OfType<ServiceBehaviorAttribute>().Single();
            behavior.IncludeExceptionDetailInFaults = true;
            
            base.OnOpening();
        }
    }
}